package com.hns.can.mainte.web;

import com.hns.can.common.web.BaseController;
import com.hns.can.mainte.entity.CommLogFileRcdEntity;
import com.hns.can.mainte.service.LoadFileService;
import com.hns.can.mainte.vo.LoadFileParamVo;
import com.hns.frame.enumrate.MsgType;
import com.hns.frame.exception.BusinessException;
import com.hns.tool.pub.FTPUtils;
import com.hns.tool.pub.PubUtil;
import com.hns.tool.pub.UtilConfig;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * 获取设备文件的控制类
 *
 * @author jeffxu
 * @email 835264047@qq.com
 */
@Controller
@RequestMapping("/loadFile")
public class LoadFileController extends BaseController {

    @Autowired
    private LoadFileService loadFileService;

    /**
     * 查询下载的文件明细
     *
     * @param {carIds, componentType = 01, beginTime, endTime}
     * @return
     * @throws Exception
     */
    @RequestMapping("/getLoadFileRcd")
    @ResponseBody
    public Object searchLoadFileRcd(LoadFileParamVo params) throws Exception {
        List<CommLogFileRcdEntity> commLogFileRcdEntityList = null;
        try {
            loadFileService.saveLoadFile(params);
            commLogFileRcdEntityList = loadFileService.getCommLogFileRcdByTimeList(params);
        } catch (Exception e) {
            throw new BusinessException(MsgType.ERROR.getFlag(), e.getMessage());
        }
        return this.getReturnResult(commLogFileRcdEntityList);
    }

    /**
     * 查询下载文件的状态
     *
     * @param {fileNames, carIds, componentType = 01, beginTime, endTime}
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/getLoadFileSt")
    @ResponseBody
    public Object getLoadFileSt(
            LoadFileParamVo params,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        List<CommLogFileRcdEntity> commLogFileRcdEntityList = null;
        try {
            if (PubUtil.isNotEmpty(params.getFileNames())) {
                String devId = loadFileService.getDevId(params);
                params.setDevId(devId);
                commLogFileRcdEntityList = loadFileService.getCommLogFileRcdByFileList(params);
            }
        } catch (Exception e) {
            throw new BusinessException(MsgType.ERROR.getFlag(), e.getMessage());
        }
        return this.getReturnResult(commLogFileRcdEntityList);
    }

    /**
     * 下载文件并且入库
     *
     * @param {carIds, fileNames, componentType = 01, ftpUrl}
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/getLoadFiles")
    @ResponseBody
    public Object getLoadFiles(
            LoadFileParamVo params,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        try {
            // 设备文件存储在FTP位置
            String ftpPath = UtilConfig.getString(params.getFtpUrl());
            params.setFtpUrl(ftpPath);
            loadFileService.loadFiles(params);
        } catch (Exception e) {
            throw new BusinessException(MsgType.ERROR.getFlag(), e.getMessage());
        }
        return this.getReturnResult();
    }

    /**
     * 下载FTP上的文件
     *
     * @param {fileNames, ftpUrl}
     * @param response
     * @throws Exception
     */
    @RequestMapping("/getFtpFile")
    public void getFtpFile(
            LoadFileParamVo params,
            HttpServletResponse response) throws Exception {

        String[] fileNames = params.getFileNames();
        String ftpPath = UtilConfig.getString(params.getFtpUrl());

        OutputStream os = response.getOutputStream();
        FTPClient ftpClient = FTPUtils.getInstance().getClient();

        try {
            for (String fileName : fileNames) {
                // 文件名重组
                fileName = fileName.substring(0, fileName.lastIndexOf(".")) + ".tar.gz";

                InputStream inputStream = ftpClient.retrieveFileStream(ftpPath + fileName);

                if (inputStream != null) {
                    response.reset();
                    response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
                    response.setContentType("application/octet-stream; charset=utf-8");
                    int bytesRead = 0;
                    byte[] buffer = new byte[8192];
                    while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                        os.write(buffer, 0, bytesRead);
                    }
                    os.flush();
                }
            }
        } finally {
            if (os != null) {
                os.close();
            }
        }
    }

}

